package com.jingyuan.client;

import com.jingyuan.common.entity.packet.OffLinePacket;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import lombok.Setter;

import java.net.InetSocketAddress;

@Setter
public class NettyHarmonyClient {
    private String serverAddress;
    private int serverPort;
    private NettyHarmonyServiceImpl nettyHarmonyService;

    public NettyHarmonyClient(NettyHarmonyServiceImpl nettyHarmonyService){
        this.nettyHarmonyService=nettyHarmonyService;
    }

    public void start() throws InterruptedException {
        Bootstrap bootstrap=new Bootstrap();
        EventLoopGroup eventLoopGroup=new NioEventLoopGroup();
        try{
            bootstrap.group(eventLoopGroup)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY,true)
                    .remoteAddress(new InetSocketAddress(serverAddress, serverPort))
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new ObjectDecoder(1024*1024,
                                    ClassResolvers.weakCachingConcurrentResolver(this.getClass().getClassLoader())));
                            ch.pipeline().addLast(new ObjectEncoder());
                            ch.pipeline().addLast(new NettyClientHandler(nettyHarmonyService));
                        }
                    });
            ChannelFuture f = bootstrap.connect().sync();
            //添加关闭钩子。优雅下线
            Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
                @Override
                public void run() {
                    if(f.isSuccess()){
                        OffLinePacket offLinePacket=new OffLinePacket();
                        PropertiesUtil readUtil=PropertiesUtil.getPropertiesUtil();
                        offLinePacket.setAddress(readUtil.getHostAddress());
                        offLinePacket.setPort(readUtil.getPort());
                        nettyHarmonyService.offline(offLinePacket);
                    }
                }
            }));
            f.channel().closeFuture().sync();
        }finally {
            eventLoopGroup.shutdownGracefully().sync();
        }

    }

//    public static void main(String[] args) throws InterruptedException {
//        NettyHarmonyClient client=new NettyHarmonyClient();
//        client.setServerAddress("127.0.0.1");
//        client.setServerPort(9898);
//        client.start();
//    }
}
